package com.ant.storage.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ant.storage.common.ContextHolder;
import com.ant.storage.common.ResultVo;
import com.ant.storage.dto.UserInfoDto;
import com.ant.storage.pojo.UserInfo;
import com.ant.storage.service.IUserInfoService;
import com.ant.storage.utils.RequestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hzd
 * @version 1.0
 * @date 2023/7/13 16:56
 */
@RestController
@RequestMapping("/login")
@Api(tags = "登录接口")
public class LoginController {

    @Autowired
    IUserInfoService userInfoService;

    // 在需要使用上下文的地方直接注入，前提，被spring管理
    @Autowired
    public ServletContext servletContext;

    @ApiOperation(value = "电脑登录")
    @PostMapping()
    public ResultVo login(@RequestBody UserInfoDto dto) throws Exception {
        servletContext.removeAttribute("userInfo");
        servletContext.removeAttribute("roles");
        Map<String, Object> param = new HashMap<>();
        param.put("tel", dto.getTel());
        param.put("password", dto.getPassword());
        String str = RequestUtil.post("/userSystem/login/loginByManager", param, null);

        JSONObject jsonObject1 = JSON.parseObject(str);
        Integer code = (Integer) jsonObject1.get("code");
        if (code == 200) {
            String data = jsonObject1.get("data").toString();
            JSONObject dataObject = JSONObject.parseObject(data);
            String user = dataObject.get("user").toString();
            JSONObject userObject = JSONObject.parseObject(user);
            String userId = userObject.get("id").toString();
            ContextHolder.setUserId(Long.valueOf(userId));
            UserInfo one = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("name_id",
                    Integer.valueOf(userId)));
            if (one == null) {
                UserInfo userInfo = new UserInfo();
                userInfo.setNameId(Integer.valueOf(userId));
                userInfo.setUserName(userObject.get("name").toString());
                userInfo.setTel(userObject.get("tel").toString());
                userInfo.setToken(dataObject.get("token").toString());
                userInfo.setUserMsg(user);
                userInfo.setCreationTime(new Date());
                userInfoService.save(userInfo);
            } else {
                one.setToken(dataObject.get("token").toString());
                one.setUserMsg(user);
                userInfoService.updateById(one);
            }
            return ResultVo.success(JSONObject.parseObject(str));
        } else {
            return ResultVo.fail(jsonObject1.get("msg").toString());
        }
    }


    @ApiOperation(value = "电脑登录")
    @PostMapping("/findLogin")
    public ResultVo findLogin(@RequestBody UserInfoDto dto) throws Exception {
        servletContext.removeAttribute("userInfo");
        servletContext.removeAttribute("roles");
        UserInfo userInfo = userInfoService.findLogin(dto);
        if (userInfo == null) {
            return ResultVo.fail("登录失败");
        }
        return ResultVo.success("登录成功", userInfo);
    }

    @ApiOperation(value = "小程序登录")
    @PostMapping("/loginApplet")
    public ResultVo loginApplet(@RequestBody UserInfoDto dto) throws Exception {
        servletContext.removeAttribute("userInfo");
        servletContext.removeAttribute("roles");
        Map<String, Object> param = new HashMap<>();
        param.put("tel", dto.getTel());
        param.put("password", dto.getPassword());
        String str = RequestUtil.post("/userSystem/login/loginByManager", param, null);
        JSONObject jsonObject1 = JSON.parseObject(str);
        Integer code = (Integer) jsonObject1.get("code");
        if (code == 200) {
            String data = jsonObject1.get("data").toString();
            JSONObject dataObject = JSONObject.parseObject(data);
            String user = dataObject.get("user").toString();
            JSONObject userObject = JSONObject.parseObject(user);
            String userId = userObject.get("id").toString();
            ContextHolder.setUserId(Long.valueOf(userId));
            UserInfo one = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("name_id",
                    Integer.valueOf(userId)));
            if (one == null) {
                UserInfo userInfo = new UserInfo();
                userInfo.setNameId(Integer.valueOf(userId));
                userInfo.setUserName(userObject.get("name").toString());
                userInfo.setTel(userObject.get("tel").toString());
                userInfo.setToken(dataObject.get("token").toString());
                userInfo.setUserMsg(user);
                userInfo.setCreationTime(new Date());
                userInfoService.save(userInfo);
                servletContext.setAttribute("userInfo", userInfo);
            } else {
                servletContext.setAttribute("userInfo", one);
                one.setToken(dataObject.get("token").toString());
                one.setUserMsg(user);
                userInfoService.updateById(one);
            }
            return ResultVo.success(JSONObject.parseObject(str));
        } else {
            return ResultVo.fail(jsonObject1.get("msg").toString());
        }
    }


    @ApiOperation(value = "退出登录")
    @PostMapping("/loginOut")
    public ResultVo loginOut() throws Exception {
        String str = RequestUtil.post("/userSystem/login/logout", null, null);
        JSONObject object = JSON.parseObject(str);
        Integer code = (Integer) object.get("code");
        if (code == 200) {
            servletContext.removeAttribute("userInfo");
            servletContext.removeAttribute("roles");
            return ResultVo.success(JSONObject.parseObject(str));
        } else {
            return ResultVo.fail(object.get("msg").toString());
        }
    }


    @ApiOperation(value = "一线小程序登录")
    @PostMapping("/aLineOfLogin")
    public ResultVo aLineOfLogin(@RequestBody UserInfoDto dto) throws Exception {
        UserInfo userInfo = userInfoService.aLineOfLogin(dto);
        return ResultVo.success("", userInfo);
    }

    @ApiOperation(value = "获取验证码")
    @PostMapping("/getCode")
    public ResultVo findCode(@RequestBody UserInfoDto dto) throws Exception {
        String code = userInfoService.findCode(dto);
        return ResultVo.success("", code);
    }


    @ApiOperation(value = "退出登录")
    @PostMapping("/getText")
    public ResultVo getText(@RequestBody UserInfoDto dto) throws Exception {
        servletContext.removeAttribute("userInfo");
        servletContext.removeAttribute("roles");
        UserInfo userInfo = userInfoService.login(dto);
        return ResultVo.success("退出登录", userInfo);
    }

}
